package com.example.demo.controller;

import com.example.demo.commons.Result;
import com.example.demo.commons.ResultEnum;
import com.example.demo.entity.User;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.example.demo.commons.LoginConstants.DEMO_TOKEN;

/**
 * @Author linjl
 * @Date 2023-06-17
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static Map<Integer, User> userMap;


    static {
        userMap = new HashMap<>(16);
        userMap.put(1001, new User(1001, "lin", 18, "Java"));
        userMap.put(1002, new User(1002, "陈逸", 19, "Python"));
        userMap.put(1003, new User(1003, "绪风", 20, "PHP"));
        userMap.put(1004, new User(1004, "溪岚花", 21, "Kotlin"));
    }


    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable Integer id, @RequestHeader(value = "Authentication", required = false) String token) {
        if (DEMO_TOKEN.equals(token)) {
            User user = userMap.getOrDefault(id, null);
            return Result.success(user);
        } else {
            return Result.error("请登录后再尝试");
        }

    }

    @PostMapping
    public Result updateUser(@RequestBody User user, @RequestHeader(value = "Authentication", required = false) String token) {
        if (DEMO_TOKEN.equals(token)) {
            userMap.put(user.getId(), user);
            return Result.success("修改成功");
        } else {
            return Result.error("请登录后再尝试");
        }
    }

}
